package com.jshoperxms.websocket;

import com.jshoperxms.SpringUtil;
import com.jshoperxms.controller.utils.json.GsonJson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by sdywcd on 2018/12/11.
 * Des:
 */
@ServerEndpoint(value = "/ancientmatchwebsocket/{matchId}/{userCode}")
@Component
public class YdAncientMatchWebSocket {

    private AncientMatchService ancientMatchService= SpringUtil.getBean(AncientMatchService.class);
    /**
     * 在线人数
     */
    public static int onlineNumber = 0;

    private static ConcurrentHashMap<String,MatchVo> webSocketMap = new ConcurrentHashMap<String,MatchVo>();//建立连接的方法

    @OnOpen
    public void onOpen(Session session,@PathParam("matchId") String matchId, @PathParam("userCode") String userCode)
    {

        MatchVo mv=webSocketMap.get("matchId");
        if(mv==null){
            mv=new MatchVo();
            mv.setMatchid(matchId);
            mv.setHomewxopenid(userCode);
            mv.setHomesession(session);
            webSocketMap.put(matchId,mv);
            addOnlineCount();
            System.out.println("有新连接加入！ 当前在线人数" + onlineNumber);
        }else {
            if(StringUtils.isNotBlank(mv.getAwaywxopenid())){
                if(!StringUtils.equals(mv.getAwaywxopenid(),userCode)){
                    ActionRuleVo msg=new ActionRuleVo();
                    msg.setAction(ActionKey.AWAYHAVE);
                    msg.setResults("比赛已经开始");
                    sendMessage(GsonJson.parseDataToJson(msg),session);
                }
            }else{
                //比赛存在
                mv.setAwaywxopenid(userCode);
                mv.setAwaysession(session);
            }

            System.out.println("比赛还在"+mv.getMatchid());
        }

    }
    @OnClose
    public void onClose(Session session)
    {
        Map<String, String> map = session.getPathParameters();
        webSocketMap.remove(map.get("matchId")); //从set中删除
        subOnlineCount(); //在线数减
        System.out.println("有连接关闭！ 当前在线人数" + onlineNumber);
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        System.out.println("收到手机上的消息了==="+message);
//获取用户ID
        Map<String, String> map = session.getPathParameters();
        String matchId = map.get("matchId");
        MatchVo matchVo=webSocketMap.get(matchId);
        ActionRuleVo actionRuleVo=GsonJson.parsejsonToObject(message,ActionRuleVo.class);
        if(actionRuleVo!=null){
            if(StringUtils.equals(actionRuleVo.getMatchmodel(),"single")){
                //单人
                ActionRuleVo result=switchAction(actionRuleVo);
                sendMessage(GsonJson.parseDataToJson(result),matchVo.getHomesession());
            }
            if(StringUtils.equals(actionRuleVo.getMatchmodel(),"battle")){
                //对战
                //比对返送过来的wxopenid来判断使用的session
                //如果是发起方
                if(StringUtils.equals(matchVo.getHomewxopenid(),actionRuleVo.getWxopenid())){
                    ActionRuleVo result=switchAction(actionRuleVo);
                    sendMessage(GsonJson.parseDataToJson(result),matchVo.getHomesession());
                }
                //如果是迎战方
                if(StringUtils.equals(matchVo.getAwaywxopenid(),actionRuleVo.getWxopenid())){

                }

            }

        }
    }

    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message,Session session) {
        session.getAsyncRemote().sendText(message);
    }





    public ActionRuleVo switchAction(ActionRuleVo actions){

        switch (actions.getAction()) {
            case ActionKey.WELCOME:
                actions.setResults("欢迎进入古诗文大挑战");
                break;
            case ActionKey.CREATESINGLEMATCHRD:
                actions.setResults(GsonJson.parseDataToJson(ancientMatchService.createMatchRd(actions)));
                break;
            case ActionKey.CREATEBATTLEMATCHRD:
                actions.setResults(GsonJson.parseDataToJson(ancientMatchService.createMatchRd(actions)));
                break;
            case ActionKey.CALSCORETHANUPDATEMATCH:
                actions.setResults(GsonJson.parseDataToJson(ancientMatchService.updateSingleMatchInfo(actions)));
                break;
            default:
                break;
        }
        return actions;
    }



    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }
    public static synchronized void addOnlineCount() {
        YdAncientMatchWebSocket.onlineNumber++;
    }
    public static synchronized void subOnlineCount() {
        YdAncientMatchWebSocket.onlineNumber--;
    }

}
